package com.ls.herostory.util;

import org.apache.ibatis.builder.xml.XMLMapperBuilder;
import org.apache.ibatis.datasource.pooled.PooledDataSource;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.mapping.Environment;
import org.apache.ibatis.session.Configuration;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.apache.ibatis.transaction.TransactionFactory;
import org.apache.ibatis.transaction.jdbc.JdbcTransactionFactory;

import java.io.IOException;
import java.io.InputStream;

/**
 * @author liangsu
 * @version v1.0
 * @Description
 * @Date 2020/10/14 9:25
 * @since
 */
public class SqlSessionFactoryUtils {

    private static SqlSessionFactoryUtils sqlSessionFactoryUtils = new SqlSessionFactoryUtils();

    private SqlSessionFactory sqlSessionFactory;

    private SqlSessionFactoryUtils(){
        PooledDataSource dataSource = new PooledDataSource();
        dataSource.setDriver("com.mysql.jdbc.Driver");
        dataSource.setUrl("jdbc:mysql://192.168.10.241:18010/test");
        dataSource.setUsername("root");
        dataSource.setPassword("Cy*123456");

        TransactionFactory transactionFactory = new JdbcTransactionFactory();
        Environment environment = new Environment("development", transactionFactory, dataSource);

        Configuration configuration = new Configuration(environment);

        try {
            // 添加mapper
            InputStream urlAsStream = Resources.getResourceAsStream("mapper/user.xml");
            XMLMapperBuilder xmlMapperBuilder = new XMLMapperBuilder(urlAsStream,
                    configuration, "user.xml", configuration.getSqlFragments());
            xmlMapperBuilder.parse();

            sqlSessionFactory =  new SqlSessionFactoryBuilder().build(configuration);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static SqlSessionFactory getSqlSessionFactory(){
        return sqlSessionFactoryUtils.sqlSessionFactory;
    }



}
